package com.chidopi.market.aa.actions;

import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.navigator.menu.MenuComponent;
import net.sf.navigator.menu.MenuRepository;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.chidopi.cdf.struts1actions.CdfDispatchAction;
import com.chidopi.cdf.util.ModelContextFactory;
import com.chidopi.market.aa.service.IPermissionService;
import com.chidopi.market.util.ClassUtils;
import com.chidopi.market.util.IPasswordState;


public class MainAction extends CdfDispatchAction {
	private static Logger logger = LoggerFactory.getLogger(MainAction.class);
	private IPermissionService permissionService;

	public ActionForward main(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		MenuRepository repository = null;
		String username = (String) request.getSession().getAttribute("username");
				
		Object obj  = ClassUtils.getUserDetails();
		boolean needEncode = false;
		if(ClassUtils.hasInterface(obj,IPasswordState.class))
			needEncode = ((IPasswordState)obj).isPassNeedEncode();
		
		logger.debug("NeedEncode: " + needEncode);
		logger.debug("username=" + username);
		try {
			this.permissionService =
				ModelContextFactory.getT("permissionService", IPermissionService.class);
			
			if(needEncode){
				repository = this.permissionService.getRepositoryOnlyPass(username);
			}else{				
				repository = this.permissionService.getRepository(username);
			}
		} catch (Exception e) {
			logger.warn("getMenu", e);
		}
		if (null == repository) repository = new MenuRepository();
		ServletContext sc = request.getSession().getServletContext();
		MenuRepository defaultRepository =
			(MenuRepository)sc.getAttribute(MenuRepository.MENU_REPOSITORY_KEY);
		repository.setDisplayers(defaultRepository.getDisplayers());
		this.debugPrint(repository);
		request.getSession().setAttribute("repository", repository);
		return mapping.findForward("success");
	}

	@SuppressWarnings("unchecked")
	private void debugPrint(MenuRepository repository) {
		logger.debug("depth=" + repository.getMenuDepth());
		Set<String> set = repository.getMenuNames();
		for (String menuName : set) {
			MenuComponent mc = repository.getMenu(menuName);
			logger.debug("url=" + mc.getLocation());
			logger.debug(menuName + " >> " + mc.getTitle() + " of " +
					(mc.getParent() != null ? mc.getParent().getTitle() : "Super"));
		}
	}
}
